package com.maimang.platform.tool;

import com.maimang.platform.common.config.Global;
import com.maimang.platform.common.utils.http.HttpUtils;
import com.maimang.platform.json.JSON;
import com.maimang.platform.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取地址类
 *
 * @author Rocky
 */
public class ToolAddress {
	private static final Logger log = LoggerFactory.getLogger(ToolAddress.class);

	public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

	public static String getRealAddressByIP(String ip) {
		String address = "XX XX";

		// 内网不查询
		if (ToolIP.internalIp(ip)) {
			return "内网IP";
		}
		if (Global.isAddressEnabled()) {
			String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip);
			if (StringUtils.isEmpty(rspStr)) {
				log.error("获取地理位置异常 {}", ip);
				return address;
			}
			JSONObject obj;
			try {
				obj = JSON.unmarshal(rspStr, JSONObject.class);
				JSONObject data = obj.getObj("data");
				String country = data.getStr("country");
				String region = data.getStr("region");
				String city = data.getStr("city");
				address = com.maimang.platform.lang.StringUtils.format("{}/{}/{}", country, region, city);
			} catch (Exception e) {
				log.error("获取地理位置异常 {}", ip);
			}
		}
		return address;
	}
}
